package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.sun.org.apache.bcel.internal.generic.LADD;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.regexp.internal.RE;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wc.L
 * @date 2022/4/26 15:48
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DisController {
    @Resource
    private DishService dishService;
    @Resource
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page();
        //构造条件筛选器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);
        //拷贝,因为dish对象的属性不完全支持页面需要显示的字段
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        //处理分类名称.
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            BeanUtils.copyProperties(item, dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //清理redis缓存
        updateRedis(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 单个删除或者批量删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.delWithFlavorByID(ids);
        //第一种可以清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

    /**
     * 停售操作
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> update0(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("停售操作成功");
    }

    /**
     * 启售操作
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> update1(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("启售操作成功");
    }

    /**
     * 修改时候 根据id获取原数据信息
     *
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //清理redis缓存
        updateRedis(dishDto);
        return R.success("修改成功");
    }

    //清理redis缓存
    private void updateRedis(DishDto dishDto) {

             /*
              //第一种可以清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        */
        //第二种可以清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

    }

    //套餐相关搜索菜品接口
    @GetMapping("/list")
    public R<List<DishDto>> getList(Dish dish) {
        List<DishDto> dishDtoList = null;
        //从redis中获取缓存数据
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844303408574465_1
        //如果存在直接返回,无需查询数据库
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (!CollectionUtils.isEmpty(dishDtoList)) {
            return R.success(dishDtoList);
        }
        //不存在需要查询数据库,并把查询到的加入到redis缓存
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        dishWrapper.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        dishWrapper.eq(Dish::getStatus, 1);
        dishWrapper.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishWrapper);
        dishDtoList = list.stream().map((item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> quwrapper = new LambdaQueryWrapper<>();
            quwrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list1 = dishFlavorService.list(quwrapper);
            dishDto.setFlavors(list1);
            return dishDto;
        })).collect(Collectors.toList());
        //并把查询到的加入到redis缓存
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
